package com.scau.ums.controller;

import com.scau.ums.model.PwdInfo;
import com.scau.ums.model.User;
import com.scau.ums.service.UserInfo;
import com.scau.ums.service.factory.UserInfoImpFactory;
import com.scau.ums.service.imp.password.CommonPasswordImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * author: 莫伟杰
 * date： 2019/8/7 11:34
 */
@Controller
public class UserPasswordController {

    private UserInfoImpFactory userInfoImpFactory;
    private CommonPasswordImp passwordImp;

    @Autowired
    public UserPasswordController(UserInfoImpFactory userInfoImpFactory, CommonPasswordImp passwordImp) {
        this.userInfoImpFactory = userInfoImpFactory;
        this.passwordImp = passwordImp;
    }

    @RequestMapping(value = "/changePassword",method = RequestMethod.GET)
    public String toChangePwd()
    {
        return "changePwd";
    }

    @RequestMapping(value = "/changePassword",method = RequestMethod.POST)
    @ResponseBody
    public Integer commitPassword(HttpServletRequest request,@RequestBody PwdInfo pwdInfo)
    {
        String userId = (String) request.getSession().getAttribute("USER_ID");
        Integer userType = (Integer) request.getSession().getAttribute("USER_TYPE");
        //为passwordImp指定用户类型
        passwordImp.setUserType(userType);
        UserInfo userInfo = userInfoImpFactory.getUserInfoImp(userType);
        User user = userInfo.getUser(userId);
        if(user==null||!passwordImp.matches(pwdInfo.pwdOld,user.getPassword()))
        {
            return 1;
        }
        else
        {
            if(!pwdInfo.pwdNew.equals(pwdInfo.pwdConfirm)) return 2;
            if(passwordImp.changePassword(userId,pwdInfo.pwdOld,pwdInfo.pwdNew)) return 0;
            return -1;
        }
        //成功：0，密码错误：1，密码不一致：2，未知错误：-1
    }
}
